<template>
  <div class="">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 用户卡片视图区域 -->
    <el-card class="box-card">
      <!-- 用户搜索 -->
      <el-row :gutter="15">
        <el-col :span="8" :offset="0">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 用户添加 -->
        <el-col :span="5" :offset="0">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="users" border stripe style="width: 100%">
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column prop="username" label="姓名" width="180" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="mobile" label="电话" />
        <el-table-column prop="role_name" label="角色" width="180" />
        <!-- 修改用户状态 -->
        <el-table-column label="状态" width="180">
          <template v-slot="slotProps">
            <el-switch v-model="slotProps.row.mg_state" active-color="#13ce66" active-text="使上线" inactive-text="使下线" @change="userStateChanged(slotProps.row)" />
          </template>
        </el-table-column>
        <!-- 对用户的可执行操作 -->
        <el-table-column label="操作">
          <template v-slot="scope">
            <!-- 修改用户 -->
            <el-tooltip effect="dark" content="修改用户信息" placement="top" :open-delay="500" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="small" @click="showEditDialog(scope.row.id)" />
            </el-tooltip>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :open-delay="500" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="small" @click="setRole(scope.row)" />
            </el-tooltip>
            <!-- 删除用户 -->
            <el-tooltip effect="dark" content="删除用户" placement="top" :open-delay="500" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="small" @click="removeUserById(scope.row.id)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="page">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 3, 4, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total" />
      </div>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="40%" @close="addDialogClosed" :close-on-click-modal="false">
      <!-- 添加用户的表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户信息的对话框 -->
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="50%" :close-on-click-modal="false" @close="editDialogClosed">
      <!-- 修改用户信息的表单 -->
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" :close-on-click-modal="false" width="50%" @close="setRoleDialogClosed">
      <div class="allotRole">
        <p>当前用户：{{ userInfo.username }}</p>
        <p>当前角色：{{ userInfo.role_name }}</p>
        <p>
          分配角色：
          <!-- select选择器 -->
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    // 自定义邮箱号验证规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱格式"));
    };
    // 自定义手机号验证规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      // 获取用户列表的请求参数对象
      queryInfo: {
        // 查询的参数，可为空
        query: "",
        // 当前页数
        pagenum: 1,
        // 每页的条目数
        pagesize: 10,
      },
      // 获取到的用户
      users: [],
      // 获取到用户总数
      total: 0,
      // 是否显示添加用户对话框
      addDialogVisible: false,
      // 添加用户的表单的数据对象
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 添加用户的表单的验证规则
      addFormRules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 2,
            max: 10,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            validator: checkEmail,
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            validator: checkMobile,
            trigger: "blur",
          },
        ],
      },
      // 是否显示修改用户信息的对话框
      editDialogVisible: false,
      // 点击修改按钮后获取到的可修改用户信息
      editForm: {},
      // 修改用户信息的表单的验证规则
      editFormRules: {
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            validator: checkEmail,
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            validator: checkMobile,
            trigger: "blur",
          },
        ],
      },
      // 分配用户角色对话框的显示
      setRoleDialogVisible: false,
      // 被分配权限的用户信息
      userInfo: {},
      // 可分配的角色的列表
      rolesList: [],
      // 用户分配的新角色的id
      selectedRoleId: "",
    };
  },
  created() {
    // 组件创建完成就获取用户列表数据
    this.getUserList();
  },
  methods: {
    // 请求用户列表数据
    async getUserList() {
      // 请求第一页数据
      const { data: res } = await this.$request.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表出错");
      // 保存用户数据和总数
      this.users = res.data.users;
      this.total = res.data.total;
    },
    // 监听 pagesize 改变，重新发起请求
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监听 pagenum改变的事件，重新发起请求
    handleCurrentChange(currentPage) {
      this.queryInfo.pagenum = currentPage;
      this.getUserList();
    },
    // 改变用户状态，参数为那一行的用户信息
    async userStateChanged(userInfo) {
      // 发起更新用户状态的请求
      const { data: res } = await this.$request.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("更新用户状态失败");
      }
      this.$message.success("更新用户状态成功");
    },
    // 监听添加用户对话框的关闭，重置里面的表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击按钮添加用户，重新获取用户数据
    addUser() {
      // 表单验证是否通过
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("添加用户参数错误");
        // 发起添加用户的请求
        const { data: res } = await this.$request.post("users", this.addForm);
        if (res.meta.status !== 201)
          return this.$message.error("服务器错误，添加用户失败");
        this.$message.success("添加用户成功");
        this.addDialogVisible = false;
        this.getUserList();
      });
    },
    // 展示编辑用户信息的对话框
    async showEditDialog(id) {
      // 通过 id 请求这个用户的数据
      const { data: res } = await this.$request(`users/${id}`);
      if (res.meta.status !== 200) {
        return ythis.$message.error("服务器错误，查询用户信息失败");
      }
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 监听编辑用户对话框的关闭，重置里面的表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 点击确定按钮，修改用户的数据
    editUserInfo() {
      // 验证表单
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("填写信息有误，请修改后再提交");
        // 发起修改用户数据的请求
        const { data: res } = await this.$request.put(
          `users/${this.editForm.id}`,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("服务器错误，更新用户信息失败");
        }
        this.editDialogVisible = false;
        this.getUserList();
        this.$message.success("更新用户信息成功");
      });
    },
    // 点击删除按钮，根据用户id删除用户
    async removeUserById(id) {
      const confirmResult = await this.$confirm("是否删除该用户", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除用户");
      }
      const { data: res } = await this.$request.delete(`users/${id}`);
      if (res.meta.status !== 200) {
        return this.$message.error("服务器错误，删除用户失败");
      }
      this.$message({
        type: "success",
        message: "删除成功!",
      });
      this.getUserList();
    },
    // 点击角色分配按钮显示分配角色的对话框
    async setRole(userInfo) {
      this.userInfo = userInfo;
      // 请求角色列表
      const { data: res } = await this.$request.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.erro("服务器错误，分配角色列表失败");
      }
      this.rolesList = res.data;
      this.setRoleDialogVisible = true;
    },
    // 点击确定按钮，保存用户的角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) return this.$message.error("请选择一个角色");
      // 发起保存角色的请求
      const { data: res } = await this.$request.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId,
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("服务器错误，分配角色失败");
      this.$message.success("分配角色成功");
      this.getUserList();
      this.setRoleDialogVisible = false;
    },
    // 监听分配角色对话框的关闭事件，并清除临时的当前用户数据
    setRoleDialogClosed() {
      this.userInfo = {};
      this.selectedRoleId = "";
    },
  },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}

.el-card {
  box-shadow: 0px 0px 1px rgba(0, 0, 0, 0.15) !important;
}

.el-table {
  margin-top: 15px;
  font-size: 0.8rem;
}

.allotRole {
  p {
    margin: 20px 0 0 0;
    line-height: 1rem;
    font-weight: 800;
  }
}
</style>
